/*
 * Copyright (c) 2015 elion All Rights Reserved.
 */
package com.guoyu.project.common.velocity;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;

/**
 * VelocitySupports
 *
 * @author: xblibo Date: 2015/5/18 Time: 13:49
 */
public class VelocitySupports {
    /**
     *
     */
    static String BLOCK_PRE = "__vm_override__";
    /**
     * 当前override节点
     */
    static String OVERRIDE_CURRENT_NODE = "__vm_current_override_node__";

    /**
     * 获取override变量名称
     * 
     * @param name
     * @return
     */
    static String getOverrideVariableName(String name) {
        return BLOCK_PRE + name;
    }

    /**
     *
     * @param context
     * @param node
     * @param argumentIndex
     * @param directive
     * @return
     * @throws ParseErrorException
     */
    static String getRequiredArgument(InternalContextAdapter context, Node node, int argumentIndex, String directive)
            throws ParseErrorException {
        SimpleNode sn_value = (SimpleNode) node.jjtGetChild(argumentIndex);
        if (sn_value == null) {
            throw new ParseErrorException("required argument is null with directive:#" + directive
                    + "(),argumentIndex=" + argumentIndex);
        }

        String value = (String) sn_value.value(context);
        if (value == null) {
            throw new ParseErrorException("required argument is null with directive:#" + directive
                    + "(),argumentIndex=" + argumentIndex);
        }
        return value;
    }

    /**
     * 设置根节点
     * 
     * @param topParentNode 根节点
     * @param node
     */
    public static void setParentForTop(OverrideNodeWrapper topParentNode, OverrideNodeWrapper node) {
        OverrideNodeWrapper top = node;
        while (top.getParentNode() != null) {
            top = top.parentNode;
        }
        // 设置父节点
        top.setParentNode(topParentNode);
    }
}
